<template>
    <view class="container">
        <!-- 搜索框区域 -->
        <view class="search-section">
            <view class="search-box">
                <view class="search-input">
                    <tui-icon name="search" :size="32" unit="rpx" color="#999"></tui-icon>
                    <input 
                        class="search-input-field" 
                        v-model="searchKeyword" 
                        placeholder="搜索商品" 
                        @confirm="goToSearch"
                        :focus="searchFocus"
                    />
                </view>
                <view class="search-btn" @tap="goToSearch">
                    <text class="search-btn-text">搜索</text>
                </view>
            </view>
        </view>

        <!-- 轮播图区域 -->
        <view class="banner-section">
            <swiper 
                :indicator-dots="true" 
                :autoplay="true" 
                :interval="5000" 
                :duration="300"
                class="banner-swiper" 
                :circular="true" 
                indicator-color="rgba(255, 255, 255, 0.6)"
                indicator-active-color="#fff">
                <swiper-item v-for="(item, index) in banner" :key="index" @tap.stop="detail">
                    <image :src="item.picUrl" class="banner-image" mode="aspectFill"></image>
                </swiper-item>
            </swiper>
        </view>

        <!-- 宫格导航 -->
        <view class="menu-grid-section">
            <view class="menu-grid">
                <view 
                    class="menu-item" 
                    v-for="(item, index) in category" 
                    :key="index" 
                    :data-key="item.name"
                    @tap="more">
                    <view class="menu-icon">
                        <image :src="item.picUrl" class="menu-image" mode="aspectFill"></image>
                    </view>
                    <view class="menu-text">{{ item.name }}</view>
                </view>
            </view>
        </view>

        <!-- 标题栏 -->
        <view class="title-section">
            <view class="title-content">
                <view class="title-text">热门商品</view>
                <view class="title-desc">大家都在买</view>
            </view>
            <view class="more-box" @tap="more">
                <text class="more-text">更多</text>
                <tui-icon name="arrowright" :size="32" unit="rpx" color="#999"></tui-icon>
            </view>
        </view>

        <!-- 商品栏 - 两列布局 -->
        <view class="goods-section">
            <view class="goods-grid">
                <view 
                    class="goods-item" 
                    v-for="(item, index) in productList" 
                    :key="index" 
                    @tap="detail(item)">
                    <view class="goods-image-wrapper">
                        <image :src="item.picUrl" class="goods-image" mode="aspectFill"></image>
                    </view>
                    <view class="goods-content">
                        <view class="goods-title">{{ item.name }}</view>
                        <view class="goods-price">
                            <text class="price-current">￥{{ fen2yuan(item.price) }}</text>
                        </view>
                        <view class="goods-sales">销量：{{ item.salesCount }}</view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 加载状态 -->
        <tui-loadmore v-if="loadding" :index="3" type="red"></tui-loadmore>
        
        <!-- 底部安全区域 -->
        <view class="safe-area-bottom"></view>

        <!-- 底部导航栏 -->
        <view class="tabbar">
            <view 
                class="tabbar-item" 
                :class="[current == index ? 'tabbar-item-active' : '']" 
                :data-index="index"
                v-for="(item, index) in tabbar" 
                :key="index"
                @tap="tabbarSwitch">
                <view class="tabbar-icon">
                    <tui-icon 
                        :name="current == index ? item.icon + '-fill' : item.icon"
                        :color="current == index ? '#FF6B35' : '#999'" 
                        :size="item.size" 
                        unit="rpx">
                    </tui-icon>
                    <!-- 购物车数量显示 -->
                    <view v-if="item.icon === 'cart' && cartCount > 0" class="cart-badge">
                        {{ cartCount > 99 ? '99+' : cartCount }}
                    </view>
                </view>
                <view class="tabbar-text">{{ item.text }}</view>
            </view>
        </view>
    </view>
</template>
<script>
    export default {
        data() {
            return {
                current: 0,
                searchKeyword: '', // 搜索关键词
                searchFocus: false, // 搜索框聚焦状态
                tabbar: [{
                    icon: 'home',
                    text: '首页',
                    size: 48
                },
                {
                    icon: 'manage',
                    text: '分类',
                    size: 54
                },
                {
                    icon: 'cart',
                    text: '购物车',
                    size: 48
                },
                {
                    icon: 'people',
                    text: '我的',
                    size: 52
                }
                ],
                hotSearch: ['休闲零食','自热火锅','小冰箱迷你'],
                banner: ['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'],
                category: [
                ],
                newProduct: [
                ],
                productList: [
                ],
                pageIndex: 1,
                loadding: false,
                pullUpOn: true,
                opacity: 1,
                cartCount: 0 // 购物车商品数量
            };
        },
        mounted() {
            this.loadBanner()
            this.loadCategoryList()
            this.loadProSalesCountList()
            this.loadPronNwProductList()
            this.loadCartCount()
            // 监听购物车变化事件
            uni.$on('refreshCart', this.loadCartCount);
        },
        onShow() {
            // 每次页面显示时刷新购物车数量
            this.loadCartCount();
        },
        beforeDestroy() {
            // 移除事件监听
            uni.$off('refreshCart', this.loadCartCount);
        },
        methods: {
            // 分转元函数，参考 yudao-mall
            fen2yuan(price) {
                return (Number(price) / 100).toFixed(2);
            },
            // 跳转到搜索页面
            goToSearch() {
                // 获取搜索关键词，如果为空则提示用户
                const keyword = this.searchKeyword.trim();
                if (!keyword) {
                    uni.showToast({
                        title: '请输入搜索关键词',
                        icon: 'none',
                        duration: 2000
                    });
                    return;
                }
                
                // 跳转到商品列表页面，并传递搜索关键词
                uni.navigateTo({
                    url: `/subPackage2/productList/productList?search=true&keyword=${encodeURIComponent(keyword)}`
                });
            },
            loadProSalesCountList() {
                var t = this
                t.$api.req(`/product/spu/page`,
                    {
                        pageNo: 1,
                        pageSize: 6,
                        sortField: 'salesCount',
                        sortAsc: false,
                    },
                    'get',"JSON",false).then(res => {
                        this.productList = res.data.list
                    });
            },
            loadPronNwProductList() {
                var t = this
                t.$api.req(`/product/spu/page`,
                    {
                        pageNo: 1,
                        pageSize: 10,
                        sortAsc: false,
                    },
                    'get',"JSON",false).then(res => {
                        this.newProduct = res.data.list
                    });
            },
            loadCategoryList() {
                var t = this
                t.$api.req(`/product/category/list`,
                    {},
                    'get',"JSON",false).then(res => {
                        // this.category = res.data
                        this.category = res.data.filter(item => item.parentId === 0);
                    });
            },
            loadBanner() {
                var t = this
                t.$api.req(`/promotion/banner/list`,
                    { position: 1 },
                    'get',"JSON",false).then(res => {
                        this.banner = res.data
                    });
            },
            // 获取购物车商品数量
            loadCartCount() {
                this.$api.req("/trade/cart/list",{},"get","JSON",false).then((res) => {
                    if (res.code === 0) {
                        // 计算购物车有效商品总数量
                        this.cartCount = (res.data.validList || []).reduce((sum, item) => sum + item.count, 0);
                    }
                }).catch((err) => {
                    console.error('获取购物车数量失败:', err);
                    this.cartCount = 0;
                });
            },
            tabbarSwitch: function (e) {
                let index = e.currentTarget.dataset.index;
                // this.current = index;
                if (index != 0) {
                    if (index == 1) {
                        this.classify();
                    } else if (index == 2) {
                        uni.navigateTo({
                            url: '../shopcart/shopcart'
                        });
                    } else {
                        uni.navigateTo({
                            url: '../my/my'
                        });
                    }
                }
            },
            detail: function (item) {
                // banner 模块跳转到商品列表页面，不传递参数
                uni.navigateTo({
                    url: '../productList/productList'
                });
            },
            coupon() {
                uni.navigateTo({
                    url: '../coupon/coupon'
                });
            },
            classify: function () {
                uni.navigateTo({
                    url: '../classify/classify'
                });
            },
            more: function (e) {
                let key = e.currentTarget.dataset.key || '';
                // 跳转到分类页面并传递类别参数
                uni.navigateTo({
                    url: `../classify/classify?categoryName=${encodeURIComponent(key)}`
                });
            },
            search: function () {
                uni.navigateTo({
                    url: '../../news/search/search'
                });
            },
            seckill(type) {
                let url = type == 1 ? '../seckillList/seckillList' : '../seckillDetail/seckillDetail';
                // this.f.nav(url);
                this.f.nav(url)
            },
            group(type) {
                let url = type == 1 ? '../groupList/groupList' : '../groupDetail/groupDetail';
                // this.f.nav(url);
                this.f.nav(url)
            }
        },
        onPullDownRefresh: function () {
            let loadData = JSON.parse(JSON.stringify(this.productList));
            loadData = loadData.splice(0,10);
            this.productList = loadData;
            this.pageIndex = 1;
            this.pullUpOn = true;
            this.loadding = false;
            uni.stopPullDownRefresh();
        },
        // onReachBottom: function () {
        //     if (!this.pullUpOn) return;
        //     this.loadding = true;
        //     if (this.pageIndex == 4) {
        //         this.loadding = false;
        //         this.pullUpOn = false;
        //     } else {
        //         let loadData = JSON.parse(JSON.stringify(this.productList));
        //         loadData = loadData.splice(0,10);
        //         if (this.pageIndex == 1) {
        //             loadData = loadData.reverse();
        //         }
        //         this.productList = this.productList.concat(loadData);
        //         this.pageIndex = this.pageIndex + 1;
        //         this.loadding = false;
        //     }
        // },
        onPageScroll(e) {
            // #ifdef APP-PLUS
            let scrollTop = e.scrollTop;
            if (scrollTop < 0) {
                if (this.opacity > 0)
                    this.opacity = 1 - Math.abs(scrollTop) / 30;
            } else {
                this.opacity = 1
            }
            // #endif
        }
    };
</script>

<style>
    page {
        background-color: #f7f7f7;
    }

    .container {
        padding-bottom: 100rpx;
        color: #333;
    }

    /* 搜索框区域 */
    .search-section {
        padding: 20rpx 30rpx;
        background: #fff;
        margin-bottom: 20rpx;
    }

    .search-box {
        background: #f5f5f5;
        border-radius: 40rpx;
        padding: 12rpx 20rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
        height: 70rpx;
    }

    .search-input {
        display: flex;
        align-items: center;
        flex: 1;
    }

    .search-input-field {
        flex: 1;
        margin-left: 15rpx;
        font-size: 26rpx;
        color: #333;
        background: transparent;
        border: none;
        outline: none;
        height: 40rpx;
        line-height: 40rpx;
    }

    .search-input-field::placeholder {
        color: #999;
    }

    .search-btn {
        background: #FF6B35;
        border-radius: 30rpx;
        padding: 8rpx 24rpx;
        margin-left: 15rpx;
        height: 50rpx;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .search-btn-text {
        color: #fff;
        font-size: 24rpx;
        font-weight: 500;
    }

    /* 轮播图区域 */
    .banner-section {
        margin: 20rpx 30rpx;
    }

    .banner-swiper {
        width: 100%;
        height: 300rpx;
        border-radius: 12rpx;
        overflow: hidden;
    }

    .banner-image {
        width: 100%;
        height: 100%;
    }

    /* 宫格导航 */
    .menu-grid-section {
        background: #fff;
        margin: 20rpx 30rpx;
        border-radius: 12rpx;
        padding: 30rpx 20rpx;
    }

    .menu-grid {
        display: flex;
        flex-wrap: wrap;
    }

    .menu-item {
        width: 25%;
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-bottom: 30rpx;
    }

    .menu-icon {
        width: 60rpx;
        height: 60rpx;
        margin-bottom: 15rpx;
    }

    .menu-image {
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
    }

    .menu-text {
        font-size: 24rpx;
        color: #333;
        text-align: center;
    }

    /* 标题栏 */
    .title-section {
        background: #fff;
        margin: 20rpx 30rpx;
        border-radius: 12rpx;
        padding: 30rpx 20rpx 20rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .title-content {
        display: flex;
        align-items: center;
    }

    .title-text {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-right: 15rpx;
    }

    .title-desc {
        font-size: 24rpx;
        color: #999;
    }

    .more-box {
        display: flex;
        align-items: center;
        color: #999;
    }

    .more-text {
        font-size: 24rpx;
        margin-right: 8rpx;
    }

    /* 商品栏 - 两列布局 */
    .goods-section {
        background: #fff;
        margin: 0 30rpx 20rpx;
        border-radius: 12rpx;
        padding: 20rpx;
    }

    .goods-grid {
        display: flex;
        flex-wrap: wrap;
        margin: -10rpx;
    }

    .goods-item {
        width: calc(50% - 20rpx);
        margin: 10rpx;
        background: #fff;
        border-radius: 8rpx;
        overflow: hidden;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }

    .goods-image-wrapper {
        width: 100%;
        height: 200rpx;
        overflow: hidden;
    }

    .goods-image {
        width: 100%;
        height: 100%;
    }

    .goods-content {
        padding: 20rpx;
    }

    .goods-title {
        font-size: 26rpx;
        color: #333;
        margin-bottom: 15rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        line-height: 1.4;
    }

    .goods-price {
        margin-bottom: 10rpx;
    }

    .goods-sales {
        font-size: 22rpx;
        color: #999;
    }

    /* 底部导航栏 */
    .tabbar {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        height: 100rpx;
        background: #fff;
        display: flex;
        align-items: center;
        justify-content: space-around;
        z-index: 9999;
        border-top: 1rpx solid #f0f0f0;
        padding-bottom: env(safe-area-inset-bottom);
    }

    .tabbar-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 10rpx 0;
    }

    .tabbar-icon {
        margin-bottom: 8rpx;
        position: relative;
    }

    .tabbar-text {
        font-size: 20rpx;
        color: #999;
        transition: color 0.3s ease;
    }

    .tabbar-item-active .tabbar-text {
        color: #FF6B35;
        font-weight: bold;
    }

    /* 购物车数量徽章 */
    .cart-badge {
        position: absolute;
        top: -8rpx;
        right: -16rpx;
        background: #FF6B35;
        color: #fff;
        font-size: 20rpx;
        font-weight: bold;
        min-width: 32rpx;
        height: 32rpx;
        line-height: 32rpx;
        text-align: center;
        border-radius: 16rpx;
        padding: 0 8rpx;
        box-sizing: border-box;
        z-index: 10;
    }

    /* 安全区域 */
    .safe-area-bottom {
        height: env(safe-area-inset-bottom);
    }

    /* 通用样式 */
    .price-current {
        font-size: 28rpx;
        font-weight: bold;
        color: #FF6B35;
    }

    /* 轮播图指示器样式 */
    ::v-deep .banner-swiper .uni-swiper-dot {
        width: 12rpx;
        height: 12rpx;
        background: rgba(255, 255, 255, 0.6);
        border-radius: 6rpx;
        margin: 0 6rpx;
    }

    ::v-deep .banner-swiper .uni-swiper-dot-active {
        background: #fff;
        width: 24rpx;
    }
</style>